#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : version_modules.py
# @Author: Xuhao
# @Date  : 2018/4/20
# @Desc  : 

from app.Sql.SQLSession import Base
from sqlalchemy import Column, String,Integer,Date
import json
from sqlalchemy.ext.declarative import DeclarativeMeta
from app.Sql.SQLSession import Base,DataBaseConnector

class VersionControll(Base):
    __tablename__ = 'book_versionctr'
    __table_args__ = {"extend_existing": True}

    id = Column(Integer, primary_key=True, autoincrement=True)

    # 是否提示版本升级提示框
    isalert = Column(String(8))

    # 是否强制升级
    isforce = Column(String(8))

    # 版本号
    version = Column(String(8))

    # 升级信息
    updataInfo = Column(String(128))

    # 广告点击总数
    bannerCnt = Column(String(8))

    # 是否显示好评
    isShowGoodReputation = Column(String(8))

    # 跳转到appStrore连接
    appStoreURL = Column(String(128))

    # 今日能够获取到的广告数量
    validBanner = Column(Integer)

    @classmethod
    def fetch_versioninfo(cls):
        '''
        获取版本控制相关信息
        '''

        connect = DataBaseConnector()

        session = connect.get_session()

        ret = session.query(VersionControll).one()

        return json.dumps(ret, cls=new_alchemy_encoder(False, ))

    @classmethod
    def updataValidBannerData(cls):
        connect = DataBaseConnector()

        session = connect.get_session()

        session.query(VersionControll).filter(validBanner=1).first()

        session.commit()




def new_alchemy_encoder(revisit_self=False, fields_to_expand=[]):
    _visited_objs = []

    class AlchemyEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj.__class__, DeclarativeMeta):
                # don't re-visit self
                if revisit_self:
                    if obj in _visited_objs:
                        return None
                    _visited_objs.append(obj)

                # go through each field in this SQLalchemy class
                fields = {}
                for field in [x for x in dir(obj) if
                              not x.startswith('_') and x != 'metadata' and hasattr(obj.__getattribute__(x),
                                                                                    '__call__') == False]:
                    val = obj.__getattribute__(field)

                    # is this field another SQLalchemy object, or a list of SQLalchemy objects?
                    if isinstance(val.__class__, DeclarativeMeta) or (
                                    isinstance(val, list) and len(val) > 0 and isinstance(val[0].__class__,
                                                                                          DeclarativeMeta)):
                        # unless we're expanding this field, stop here
                        if field not in fields_to_expand:
                            # not expanding this field: set it to None and continue
                            fields[field] = None
                            continue

                    fields[field] = val
                # a json-encodable dict
                return fields

            return json.JSONEncoder.default(self, obj)

    return AlchemyEncoder


if __name__ == "__main__":

    print(VersionControll.fetch_versioninfo())